<template>
  <div class="working-box">
    <div class="image-area">
      <!-- <div class="tool-bar">
        <el-button type="primary" @click="submit" class="save-btn">保存</el-button>
      </div> -->
      <div class="tool-bar">
        <el-button type="primary" @click="putSysnFile" class="save-btn">同步文件</el-button>
      </div>
      <div id="canvasToolsDiv" class="canvas-tools-div">
        <div id="toolbarDiv" ref="toolbarDiv"></div>
        <div id="selectionDiv">
          <v-image :src=currImg.imgUrl v-if="currImg" alt="" />
        </div>
        <div class="file-lis-box" >
          <div class="file-lis-btn file-lis-prev" @click="pagingPrev"></div>
          <div class="file-lis" :style="{
            width: `${computePaging * 280}px`
          }">
            <ul :style="{
               left: `${computePaging * 226 * pagingIndex}px`
            }">
              <li v-for="(e,i) in filesLis" :key="e.id" :class="{ 'active': listPicActive == i }">
                <div class="img-bg" @click="setSelectImg(i)"  >
                  <v-image :src=e.imgUrl alt=""  />
                </div>
              </li>
            </ul>
          </div>
          <div class="file-lis-btn file-lis-next" @click="pagingNext"></div>
        </div>
      </div>
    </div>
    <div class="label-area">
      <h3>图片标签类型
        <span class="image-right" >{{imageLabel}}</span>
      </h3>
      <div class="l-a-serch">
      </div>
<!--      <p class="l-a-hint">请选择展示图片标签类型</p>-->
<!--      <ul class="l-a-lis">-->
<!--        <li v-for="(e, i) in tagNames" :key="i" @click="doTask(i)" :class="{ active: i == labelsActive }"-->
<!--          :style="{ color: calcColor(i) }">-->
<!--          <span class="lis-word">{{ e.name }}</span>-->
<!--          <span class="lis-shortcut">快捷键</span>-->
<!--          <span class="lis-key">{{ i + 1 }}</span>-->
<!--        </li>-->
<!--      </ul>-->
    </div>
  </div>
</template>
<script>


import { domain } from "@/config";
import { Base64 } from "js-base64";
import { getAnnFiles,getAnnFileLabel } from '@/api/annFile'
import { getAllAnnLabels } from '@/api/annLabel'
import {getAnnTaskDetail, syncFile} from '@/api/annTask.js'
import messesDialog from "@/utils/messesDialog";
import {debounce} from "@/utils/tool";

export default {
  data() {
    return {
      h: 0,
      pageNum: 1,
      pageSize: 8,
      fileIndex: 0,
      currImg: null,
      ann_task_id: this.$route.query.ann_task_id,
      dataset_id: this.$route.query.id,
      preDataFlag: false,
      tagNames: [],
      typeVal: '',
      typeMap: [],
      filesLis: [],
      preFileLis: null,
      nextFileLis: null,
      currPageNum: 1,
      nextDataFlag: false,
      perDataFlag: false,
      total:0,
      userInfo: null,
      labelsActive: 0,
      imageLabel : '无',
      label_id: '',
      listPicActive: 0,
      isFocus:false,
      pagingIndex:0,
    };
  },
  computed: {
    computePaging() {
        console.log("computePaging")
      let w = document.documentElement.clientWidth
      let navW = localStorage.getItem('menu_project') == 'false' ? 257 : 65
      let boxWidth = w - navW - 290 - 64 - 32 - 20 - 80
      if (w < 1560) {
        boxWidth = w - navW - 64 - 32 - 20 - 80
      }
      return parseInt(boxWidth / 240)
    },
  },
  methods: {
    async getAnnTask() {
      let ret = await getAnnTaskDetail({ id: this.ann_task_id })
      this.total = ret.data.total
    },
    setSelectImg(index){
        this.fileIndex = index
        this.listPicActive=this.fileIndex
        this.currImg =  this.filesLis[this.fileIndex]
      this.getFileLabel(this.currImg.id)
        this.$forceUpdate()
        console.log("fileIndex", index,this.fileIndex, this.filesLis[this.fileIndex])
    },
    calcColor(i) {
      if (this.typeMap[i] &&
        this.typeMap[i].colorObj &&
        this.typeMap[i].colorObj.rgbColor &&
        this.typeMap[i].colorObj.rgbColor.values) {

        let rgbStr = ''
        this.typeMap[i].colorObj.rgbColor.values.forEach(e => {
          rgbStr += (',' + (e * 255).toFixed(2))
        })
        return `rgb(${rgbStr.slice(1)})`
      }
    },
    async pagingPrev() {
      console.log("---fileIndex", this.fileIndex, this.currPageNum)
      if (this.fileIndex > 0) {
        this.fileIndex--
        if (this.fileIndex < 3) {
          this.getprePageData()
        }
      } else {
        if (this.preFileLis != null) {
          this.filesLis = this.preFileLis
          this.preFileLis = null
          this.currPageNum = this.currPageNum - 1
          this.fileIndex = this.filesLis.length - 1
        } else {
          await this.getprePageData()
          if (this.preFileLis != null) {
            this.filesLis = this.preFileLis
            this.preFileLis = null
            this.currPageNum = this.currPageNum - 1
            this.fileIndex = this.filesLis.length - 1
          }
        }
      }
      this.setCurrImg()
    },
    async pagingNext() {
      console.log("fileIndex", this.fileIndex, this.filesLis.length)
      if (this.fileIndex < (this.filesLis.length - 1)) {
        this.fileIndex++
        if (this.fileIndex == (this.filesLis.length - 1)) {
          this.getNextPageData()
        }
      } else {

        if (this.nextFileLis != null) {
          console.log("init filelist")
          this.filesLis = this.nextFileLis
          this.fileIndex = 0
          this.currPageNum = this.currPageNum + 1
          this.nextFileLis = null
        } else {
          if (this.currPageNum == this.total) {
            messesDialog({
              message:  `已经是最后一张`,
            })
            return
          }
          await this.getNextPageData()
          if (this.nextFileLis != null) {
            console.log("init filelist")
            this.filesLis = this.nextFileLis
            this.fileIndex = 0
            this.currPageNum = this.currPageNum + 1
            this.nextFileLis = null
          }
        }
      }
      this.setCurrImg()
    },
    setCurrImg(){
        console.log("setCurrImg")
      if(this.fileIndex<=this.filesLis.length-1){
        this.currImg = this.filesLis[this.fileIndex]
      }
      this.listPicActive=this.fileIndex
      this.getFileLabel(this.filesLis[this.fileIndex].id)

    },
    async getNextPageData() {
      if (this.currPageNum == this.total)
        return
      if (this.nextDataFlag == false) {
        try {
          this.nextDataFlag = true
          let ret = await getAnnFiles({ pageNum: this.currPageNum+1, pageSize: this.pageSize, annTaskId: this.ann_task_id })
          this.nextFileLis = ret.data.list
          this.setDataImgSrc(this.nextFileLis)
          this.nextDataFlag = false
          console.log("nextFileLis", this.nextFileLis)
        }
        catch {
          this.nextDataFlag = false
        }
      }
    },
    async getInitPageData() {
      console.log("init")
      this.currPageNum = 1
      if (this.currPageNum <= this.total) {
        let ret = await getAnnFiles({ pageNum: this.currPageNum, pageSize: this.pageSize, annTaskId: this.ann_task_id })
        this.filesLis = ret.data.list
        this.setDataImgSrc(this.filesLis)
        this.total = ret.data.total_page
        if(this.filesLis.length>0){
          this.currImg = this.filesLis[this.fileIndex]
          await this.getFileLabel(this.currImg.id)

        }

      }else if(this.total == 0){
        this.filesLis = []
      }

    },
    async putSysnFile(){
      this.myInfo =  this.$myInfo(this)
      await syncFile({
        id: this.ann_task_id,
        user_id: this.myInfo.id
      })
      await  this.getAnnTask()
      await this.getAllLabel()
      await this.getInitPageData()
      await  this.$forceUpdate()
    },
    async getLableOne(id){
      this.tagNames.forEach((e)=>{
        if(e.id== id){
          this.imageLabel = e.name
          return
        }
      })
    },
    setDataImgSrc(data){
      console.log("data",data)
      data.forEach((e, i) => {
        let image_name = e.path.substr(e.path.lastIndexOf(this.dataset_id)+this.dataset_id.length+1)
        console.log("i", i, this.getImgUrl(e.path),image_name)
        data[i].imgUrl = this.getImgUrl(image_name)
        console.log("dataimg",data[i].imgUrl)
      })
    },
    async getprePageData() {
      if (this.currPageNum ==1){
        return
      }
      if (this.preDataFlag == false) {
        try {
          this.preDataFlag = true
          let ret = await getAnnFiles({ pageNum: this.currPageNum-1, pageSize: this.pageSize, annTaskId: this.ann_task_id })
          this.preFileLis = ret.data.list
          this.setDataImgSrc(this.preFileLis)
          this.preDataFlag = false
        }
        catch {
          this.preDataFlag = false
        }
      }
    },

    async getAllLabel() {
      // let res = []
      let res = await getAllAnnLabels({ annTaskId: this.ann_task_id })
      console.log(res)
      this.tagNames = res.data
    },
    //获取文件标签
    async getFileLabel( id) {
      let res = await getAnnFileLabel({ annTaskId: this.ann_task_id,annFileId:id })
      if(res.data.list[0]!=null){
        this.label_id = res.data.list[0].ann_label_id
        await this.getLableOne(this.label_id)
      }else{
        this.imageLabel='无'
      }
      console.log("lable",this.label_id)
    },
    async doTask(i) {
      this.labelsActive = i
      // let data={
      //   ann_file_id: this.filesLis[this.fileIndex].id,
      //   ann_label_id:label.id,
      //   ann_task_id: this.ann_task_id
      // }
      // await addAnnFileLabel(data)
      // this.pagingNext()
    },
    switchover(e) {
      if (this.isFocus) return
      var currKey = 0
      e = e || event || window.event;
      currKey = e.keyCode || e.which || e.charCode;
      let codes = []

      for (let i = 49; i < 58; i++) {
        codes.push(i)
      }
      if (codes.indexOf(currKey) != -1) {
        // this.typeVal = this.typeMap[codes.indexOf(currKey)].name
        // this.chageType(this.typeVal)
        this.labelsActive = codes.indexOf(currKey)
        this.doTask(this.tagNames[this.labelsActive],this.labelsActive)
      }

      if (currKey == 83 && (e.ctrlKey || e.metaKey)) {

        debounce(this.submit, 300)()

        e.preventDefault();
        return false;
      }

      if (currKey == 83) {

        debounce(this.submit, 300)()

        e.preventDefault();
        return false;
      }
      if (currKey == 27) {
        e.preventDefault();
        return false;
      }
    },


    getImgUrl(relative_path) {
      // domain
      // Base64
      console.log("relative_path", relative_path,`${domain}file/v1/file/preview/${this.userInfo.id
      }/dataset/${this.$route.query.id
      }/${encodeURIComponent(Base64.encode(relative_path))
      }`)
      return `${domain}file/v1/file/preview/${this.userInfo.id
        }/dataset/${this.$route.query.id
        }/${encodeURIComponent(Base64.encode(relative_path))
      }`
      // return `http://localhost:3000/${relative_path}`
    },

  },
  async mounted() {
    console.log("help")
    this.h = document.documentElement.clientHeight
    let info = await this.$myInfo(this)
    this.userInfo = info
    document.addEventListener("keydown", this.switchover);
    // this.$EventBus.$emit('hideCollapse', true)
    await this.getAnnTask()
    await this.getAllLabel()
    await this.getInitPageData()
  },
  destroyed() {
    document.removeEventListener("keydown", this.switchover);
    // this.$EventBus.$emit('hideCollapse', false)
  },
};
</script>
<style lang="less" scoped>
.tool-bar {
  width: 100%;
  margin-top: 16px;
  overflow: hidden;

  .save-btn {
    float: right;
    margin-right: 16px;
  }
}
.layout {
  padding: 0 16px;
  .working-area {
    background: #fff;
    margin-top: 16px;
    padding: 16px 32px;
    box-shadow: 0px 2px 16px 0px rgba(30, 36, 128, 0.07);
    border-radius: 2px;
  }
}
.tool-bar {
  width: 100%;
  margin-top: 16px;
  overflow: hidden;
  .save-btn{
    float: right;
    margin-right: 16px;
  }
}
.working-box {
  display: flex;
  width: 100%;
  justify-content: space-between;
  .image-area {
    flex: 1;
    padding-right: 16px;
    min-width: 900px;
  }
  .label-area {
    width: 288px;
    border-left: 1px solid #e4e7ed;
    border-right: 1px solid #e4e7ed;
    h3 {
      padding: 18px 0 18px 16px;
      line-height: 20px;
      font-size: 14px;
      border-bottom: 1px solid #e4e7ed;
      position: relative;
      .add-btn {
        position: absolute;
        right: 18px;
        top: 6px;
      }
      .image-right {
        position: absolute;
        right: 18px;
        top: 20px;
        color: rgba(0, 19, 233, 0.67);
      }
    }
    .l-a-serch {
      padding: 8px 16px;
    }
    .l-a-hint {
      padding: 24px 0 0 16px;
      color: #909399;
      line-height: 20px;
    }
    .l-a-lis {
      padding: 4px 16px 0 16px;
      li {
        margin-top: 4px;
        height: 36px;
        line-height: 36px;
        border-radius: 4px;
        border: 1px solid #e3e3e3;
        padding: 0 10px;
        display: flex;
        cursor: pointer;
      }
      // span{
      //   float: left;
      // }
      .lis-word {
        // flex: 1;
        color: #303133;
        width: 170px;
        overflow: hidden;
        white-space:nowrap;
        text-overflow: ellipsis;
      }
      .lis-shortcut {
        width: 42px;
        font-size: 12px;
        color: #909399;
      }
      .lis-key {
        width: 20px;
        height: 18px;
        line-height: 18px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #c0c4cc;
        display: block;
        text-align: center;
        margin-top: 9px;
      }
      li.active,
      li:hover {
        border: 1px solid #4285f4;
      }
    }
  }
  .carousel-box {
    margin-top: 40px;
  }
}
@media screen and (max-width: 1560px) {
  .label-area {
    display: none;
  }
}
// body {
//     margin: 20px;
//     font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
// }

// #controls div {
//     margin: 20px 0;
// }

// .canvas-box{
//     height: 100%;
//     width: 100%;
// }
// #canvasToolsDiv {
//     display: grid;
//     width: 100%;
//     height: 100%;
//     grid-template-columns: 64px 1fr;
//     grid-template-rows: 100%;

//     margin:0;
//     background: rgb(64,64,64);
// }
#toolbarDiv {
    position: absolute;
    left: -28px;
    top: 0px;
    z-index: 999;
    height: 486px;
    /deep/ svg{
      width: 64px;
      height: 100%;
      margin-right:5px;
      background: #FFF;
      box-shadow: 0 0 0.5px #999, 5px 0px 10px -5px rgba(0, 0, 0, 0.8);
    }
}
#selectionDiv{
  margin-left: 30px;
  height: 600px;
}
.canvas-tools-div{
  margin-top: 16px;
  padding: 0 12px;
  position: relative;
}
.prev{
  position: absolute;
  width: 48px;
  height: 48px;
  border-radius: 24px;
  left: 10px;
  z-index: 999;
  background: url(~@/assets/img/prev.png) no-repeat center center #FFF;
  background-size: 100% 100%;
  cursor: pointer;
}
.next{
  position: absolute;
  width: 48px;
  height: 48px;
  border-radius: 24px;
  right: 10px;
  z-index: 999;
  background: url(~@/assets/img/next.png) no-repeat center center #FFF;
  background-size: 100% 100%;
  cursor: pointer;
}
// #toolbarDiv {
//     grid-row: 1;
//     grid-column: 1/2;
//     z-index: 10;
//     height: 100%;
//     /deep/ svg{
//       width: 64px;
//       height: 100%;
//       margin-right:5px;
//       background: #666;
//       box-shadow: 0 0 0.5px #999, 5px 0px 10px -5px rgb(0,0,0);
//     }
// }


// #selectionDiv {
//     grid-row: 1;
//     grid-column: 2/3;
//     justify-self: center;
//     align-self: center;
//     margin: 5px;
//     width: calc(100% - 10px);
//     height: calc(100% - 10px);
//     background: rgb(64,64,64);
// }

// #editorDiv{
//     height: calc(100% - 80px);
// }

// #editorDiv svg {
//     box-shadow: 0px 0px 0.25px #999, 0px 0px 10px rgb(0,0,0);
// }
.file-lis-box{
  border-top: 1px solid #DCDFE6;
  border-bottom: 1px solid #DCDFE6;
  margin-top: 32px;
  display: flex;
  justify-content: space-between;
  .file-lis-btn{
    // icon-next-btn.png
    // float: left;
    width: 30px;
    height: 160px;
    background: url(~@/assets/img/icon-next-btn.png) no-repeat #DCDFE6 center center;
    background-size: 30px auto;
    cursor: pointer;
  }
  .file-lis-prev{
    transform: rotate(180deg);
  }
  .file-lis{
    // float: left;
    // width: calc(100% - 80px);
    // display: flex;
    // justify-content: space-between;
    // margin: 10px 10px;
    overflow: hidden;
    height: 140px;
    position: relative;
    ul{
      display: flex;
      // justify-content: space-between;
      margin: 10px 0;
      position: absolute;
      left: 0;
      top: 0;
      transform: all .3s;
    }
    li{
      // flex: 1;
      box-sizing: border-box;
      padding: 0 8px 0 0;
      .img-bg{
        // background: #303133;
        width: 210px;
        height: 140px;
        position: relative;
        border: 2px solid #fff;
        box-sizing: border-box;
      }
      // .no-img{
      //   background: #FFF;
      // }
      img{
        display: block;
        max-width: 100%;
        max-height: 100%;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        cursor: pointer;

      }
    }
    .active{
      .img-bg{
        border: 3px solid rgba(66, 133, 244, 1);
      }
    }
  }
}
</style>
